package com.logicbus.dbcp.xscript;

import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.plugins.Segment;
import com.anysoft.util.BaseException;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import com.logicbus.dbcp.processor.Preprocessor;
import com.logicbus.dbcp.sql.DBTools;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 当不存在时进入
 *
 * @version 1.6.13.1 [20200302]
 * - 优化debug参数,读取dbcp.debug环境变量
 */
public class NotExist extends Segment {
    protected String dbconn = "dbconn";
    protected String sql;
    protected String id;
    protected Preprocessor processor = null;
    protected boolean transform = false;
    protected boolean debug = false;
    public NotExist(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);
        dbconn = PropertiesConstants.getString(p,"dbconn", dbconn);
        sql = PropertiesConstants.getRaw(p,"sql",sql);
        id = PropertiesConstants.getString(p, "id", "$" + this.getXmlTag(),true);
        debug = PropertiesConstants.getBoolean(p,"debug", PropertiesConstants.getBoolean(p,"dbcp.debug",debug,false),true);
        transform = PropertiesConstants.getBoolean(p,"transform",transform,true);
        processor = new Preprocessor(transform,sql);
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx,
                             ExecuteWatcher watcher) {
        Connection conn = ctx.getObject(dbconn);
        if (conn == null){
            throw new BaseException("core.e1001","It must be in a db context,check your together script.");
        }

        List<Object> data = new ArrayList<Object>();
        String sql = processor.process(ctx, data);

        if (debug){
            log("sql=" + sql,"debug");
            log("binded=" + data.toString(),"debug");
        }

        List<Map<String,String>> result = DBTools.list(conn, sql,data.toArray());

        if(result == null || result.size()<=0){
            super.onExecute(root, current, ctx, watcher);
        }else{
            ctx.SetValue(id, String.valueOf(result.size()));
        }
    }
}